require 'fastthread'
require 'thread'

module ESI
  class Response
    attr_reader :output

    def initialize( output )
      @lock = Mutex.new
      @count = 0
      @back_buffer = []
      @output = output
      @last_out = -1
    end

    # return's id
    def reserve_message
      @lock.synchronize do
        @back_buffer[@count]
        @count += 1
        (@count-1)
      end
    end

    def back_buffer(id,body)
      @lock.synchronize do
        @back_buffer[id] = body
      end
    end

    def send_message(body)
      @lock.synchronize do
        @back_buffer[@count] = body # buffer current message
        # roll up requests
        until @last_out == @count
          o = @back_buffer[@last_out+1]
          if o.nil?
          #  puts "buffering..."
            break
          end
          #puts "sending: #{@last_out+1}"
          @back_buffer[@last_out+1] = nil # clear it out, release memory
          @output << o
          @last_out += 1
        end
      end
      @count += 1
    end

    def flush
      # roll up requests
      tail_buffer = (@back_buffer[@last_out..@back_buffer.size]||[])
      while !tail_buffer.empty?
        o = tail_buffer.shift
        @output << o unless o.nil?
        #puts "sending: #{@count-tail_buffer.size}"
      end
    end

  end
end
